package com.clps.algorithm.chapter08.序列化和反序列化二叉树;

import com.clps.algorithm.chapter07.二叉树每层的最大值.TreeNode;

/**
 * 请设计一个算法能将二叉树序列化成一个字符串并能将该字符串反序列化出原来二叉树的算法。
 */
public class demo01 {
    public static void main(String[] args) {

    }

    public String serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }

        String leftStr = serialize(root.left);
        String rightStr = serialize(root.right);
        return root.val + "," + leftStr + "," + rightStr;
    }


    public  TreeNode deserialize(String data){
        String[] nodeStrs = data.split(",");
        int[] i = {0};
        return  dfs(nodeStrs,i);
    }

    private TreeNode dfs(String[] strs, int[] i) {
        String str = strs[i[0]];
        i[0]++;

        if(str.equals("#")){
            return null;
        }

        TreeNode node = new TreeNode(Integer.valueOf(str));
        node.left = dfs(strs,i);
        node.right = dfs(strs,i);
        return  node;
    }
}
